{
 "nbformat": 4,
 "nbformat_minor": 2,
 "metadata": {
  "language_info": {
   "name": "python",
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "version": "3.8.1-final"
  },
  "orig_nbformat": 2,
  "file_extension": ".py",
  "mimetype": "text/x-python",
  "name": "python",
  "npconvert_exporter": "python",
  "pygments_lexer": "ipython3",
  "version": 3,
  "kernelspec": {
   "name": "python38164bitbed07143d37b49c8ba24bbf4d83c1753",
   "display_name": "Python 3.8.1 64-bit"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "左叶子之和\n",
    "\n",
    "计算给定二叉树的所有左叶子之和。\n",
    "\n",
    "示例：\n",
    "```\n",
    "    3\n",
    "   / \\\n",
    "  9  20\n",
    "    /  \\\n",
    "   15   7\n",
    "\n",
    "在这个二叉树中，有两个左叶子，分别是 9 和 15，所以返回 24\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from leetcode_test import TreeNode"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我想到的解法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Solution:\n",
    "    \"\"\"\n",
    "    \"\"\"\n",
    "    def sumOfLeftLeaves(self, root: TreeNode) -> int:\n",
    "        print(\"root=\", root)\n",
    "        if not root:\n",
    "            return 0\n",
    "\n",
    "        if root.left and not root.left.left and not root.left.right:\n",
    "            # 一开始没有加 `+ self.sumOfLeftLeaves(root.right)` 直接返回了9\n",
    "            return root.left.val + self.sumOfLeftLeaves(root.right)\n",
    "        \n",
    "        return self.sumOfLeftLeaves(root.left) +  self.sumOfLeftLeaves(root.right)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "别人想到到解法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Solution:\n",
    "    \"\"\"添加关键词来判断是左节点\n",
    "    \"\"\"\n",
    "    def sumOfLeftLeaves(self, root: TreeNode) -> int:\n",
    "        \n",
    "        def helper(root: TreeNode, is_left: bool):\n",
    "            if not root:\n",
    "                return 0\n",
    "\n",
    "            if not root.left and not root.right and is_left:\n",
    "                return root.val\n",
    "            \n",
    "            return helper(root.left, True) +  helper(root.right, False)\n",
    "        return helper(root, False)"
   ]
  }
 ]
}